package com.sczc.esm27.collection.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyServer implements CommandLineRunner {

    private final Logger logger = LogManager.getLogger(getClass());

    @Value("${tcp.server.port}")
    private int tcpPort;
    @Value("${boss.thread.count}")
    private int bossCount;
    @Value("${worker.thread.count}")
    private int workerCount;
    @Value("${so.keepalive}")
    private boolean keepAlive;
    @Value("${so.backlog}")
    private int backlog;

    private void start() {
        NioEventLoopGroup bossGroup = null;
        NioEventLoopGroup workerGroup = null;
        ChannelFuture future = null;
        try {
            bossGroup = new NioEventLoopGroup(bossCount);
            workerGroup = new NioEventLoopGroup(workerCount);
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //快速复用端口
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childHandler(new NettyServerChannelInitializer())
                    .option(ChannelOption.SO_BACKLOG, backlog)
                    .childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
            // 绑定端口，开始接收进来的连接
            future = b.bind(tcpPort).sync();
            logger.info("TCP服务已启动，监听端口：" + tcpPort);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("TCP服务启动失败，监听端口：" + tcpPort);
        } finally {
            if (future != null) {
                try {
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    logger.error("channel关闭异常：", e);
                }
            }
            if (bossGroup != null) {
                //线程组资源回收
                bossGroup.shutdownGracefully();
            }
            if (workerGroup != null) {
                //线程组资源回收
                workerGroup.shutdownGracefully();
            }
        }
    }

    @Override
    public void run(String... args) throws Exception {
        start();
    }
}
